package com.cynoware.busappmas.model;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.cynoware.busappmas.ui.Distribution;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;

@SuppressLint("HandlerLeak")
public class LoadTime extends Service{
	
	private final static String TAG = "LoadTime";
    private  SurfaceView mView;
    private Paint mAddedPaint;
    private WindowManager wm;
    public static boolean isRunning = false;
    private WindowManager.LayoutParams params;
    public  int mTimeForDelay = 1000;
    private int display_w = 1440;
    private int display_h = 900;
   
    private final int mTextSize = 45;
    private int timeX = 1010;
    private int timeY = 50;
    
    private Config mConfig;

    
    private class LoadView extends SurfaceView implements SurfaceHolder.Callback {
    	
    	private SurfaceHolder surfaceHolder;
        
        private Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    updateDisplay();
                    Message m = obtainMessage(1);
                    sendMessageDelayed(m, mTimeForDelay);
                }
            }
        };

        LoadView(Context c) {
            super(c);
            

            setPadding(4, 4, 4, 4);
            int textSize = Distribution.getTopTimeSize(mTextSize,display_w)  ;      

            mAddedPaint = new Paint();
            mAddedPaint.setAntiAlias(false);
            mAddedPaint.setTextSize(textSize);
            mAddedPaint.setARGB(255, 255, 255, 255);

            surfaceHolder = this.getHolder();
            getHolder().setFormat(PixelFormat.TRANSLUCENT);
            surfaceHolder.addCallback(this);
            Log.d(TAG,"LoadView created!");
        }

        @Override
        protected void onAttachedToWindow() {
            super.onAttachedToWindow();
            mHandler.sendEmptyMessage(1);
        }

        @Override
        protected void onDetachedFromWindow() {
            super.onDetachedFromWindow();
            mHandler.removeMessages(1);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            setMeasuredDimension(display_w,display_h);
        }

        @SuppressLint({ "SimpleDateFormat", "UseValueOf" })
		public void repaint(){
           Canvas c = null;
           float x = 0;
           float y = 0;
           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");;
           Date d = new Date();
           try{
        	 String sreenSpecial = mConfig.getScreenSpecial() != null ?mConfig.getScreenSpecial().getValue().trim():"0";
             if (sreenSpecial.equals(ConfigDataModel.SCREEN_700_506_19_hz)){
               	timeY = 75;
             }
             //Log.d(TAG," timeY "+timeY);
             c = surfaceHolder.lockCanvas();
             c.drawColor(Color.TRANSPARENT,PorterDuff.Mode.CLEAR);
             x = timeX*Distribution.getScreenWRatio(display_w);
             y = timeY*Distribution.getScreenHRatio(display_h);
             c.drawText(sdf.format(d), (new   Double(x)).intValue(), (new   Double(y)).intValue(), mAddedPaint);
           } finally {
              if(c != null){
                surfaceHolder.unlockCanvasAndPost(c);
              }
           }
        }
        void updateDisplay() {        	
             repaint();
        }
       public void surfaceDestroyed (SurfaceHolder holder){}
       public void surfaceCreated (SurfaceHolder holder){}
       public void surfaceChanged (SurfaceHolder holder, int format, int width, int height){}

    }

    
    @SuppressLint("InlinedApi")
	@Override
    public void onCreate() {
    	super.onCreate();
    	mConfig = Config.instance(getContentResolver());
    	
    	Point point = new Point();  
    	((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getRealSize(point);  
        
        Log.d(TAG,"the screen real size is "+point.toString());  
              
        display_w = point.x;
        display_h = point.y;    
    	
        params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
            WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
            PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.RIGHT | Gravity.TOP;
        mView = new LoadView(this);
        wm = (WindowManager)getSystemService(WINDOW_SERVICE);
        wm.addView(mView, params);
        isRunning = true;
        Point size = new Point(0,0);
        wm.getDefaultDisplay().getSize(size);
        Log.d(TAG,"create time");
    }
    

    
    @Override
    public void onDestroy() {
        super.onDestroy();
        ((WindowManager)getSystemService(WINDOW_SERVICE)).removeView(mView);
        mView = null;
        isRunning = false;
    }


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

        
}